package com.example.publice.aop;

import java.lang.reflect.Method;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import com.example.publice.validate.DataValidator;

@Aspect
@Component
public class ValidationAop {

	@Pointcut("@within(org.springframework.stereotype.Controller) && ("
			+ "@annotation(org.springframework.web.bind.annotation.GetMapping) ||"
			+ "@annotation(org.springframework.web.bind.annotation.PostMapping) ||"
			+ "@annotation(org.springframework.web.bind.annotation.RequestMapping))")
	public void print() {

	}

	@Around("print()")
	public Object validate(ProceedingJoinPoint pjp) throws Throwable {
		Method method = ((MethodSignature) pjp.getSignature()).getMethod();
		com.example.publice.annotation.DataValidate ann = method
				.getAnnotation(com.example.publice.annotation.DataValidate.class);
		if(ann!=null){
			Class<? extends com.example.publice.validate.DataValidator>[] validators = ann.value();
			Object[] args = pjp.getArgs();
			for (Class<? extends DataValidator> validatorClass : validators) {
				DataValidator datav = validatorClass.newInstance();
				datav.setData(args);
				datav.validate();
			}
		}
		return pjp.proceed();
	}

}
